package com.blog.controller;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.blog.bean.Blog;
import com.blog.bean.Record;
import com.blog.bean.User;
import com.blog.dao.IBlogDao;
import com.blog.dao.IRecordDao;
import com.blog.dao.IUserDao;

/**
 * @className: LoginController
 * @description: 
 * @author: HCl
 * @createTime: 2020年6月7日 上午10:04:50
 */
@Controller
public class LoginController {

	@Autowired 
	private IUserDao userDao;
	@Autowired
	private IRecordDao recordDao;
	@Autowired
	private IBlogDao blogDao;
	
	@RequestMapping(value = "doLogin",method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> doLogin(String username,String password,HttpSession session,HttpServletRequest request){
		Map<String,	Object> reMap = new HashMap<String, Object>();
		
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		
		User logingUser = null;
		
		logingUser = userDao.selectUserByUsernameAndPassword(user); 
		String codeString = request.getParameter("loginCode");
		System.out.println(codeString); 
		if (!codeString.equals(session.getAttribute("CHECKCODE_SERVER")) ) {
			reMap.put("state", 0);
			reMap.put("msg","验证码错误，请输入图片两数之和！");
			return reMap;
		}
		if (logingUser == null) {
			reMap.put("state", 0);
			reMap.put("msg","用户名或密码错误！");
		} else {

			session.setAttribute("loginUser", logingUser);
			reMap.put("state", 1);
			reMap.put("msg", "登录成功，正在跳转页面......");
			reMap.put("url", "index");
			
			//查询用户最近访问 
			List<Record> records = recordDao.selectAllRecordByUserId(logingUser.getId());
			List<Blog> historyBlogs = new LinkedList<Blog>();
			Blog tempBlog;
			for (int i = 0; i < records.size(); i++) {
				
				tempBlog = blogDao.selectBlogById(records.get(i).getBlog());
				if (tempBlog == null) {
					continue;
				}
				tempBlog.setCreatedate(records.get(i).getTime());
				historyBlogs.add(tempBlog);
				if(i == 4)break; 
				
				
				
				
				
			}
			session.setAttribute("history_blog", historyBlogs);
			
			
		}
		return reMap;
	}
	
	@RequestMapping(value = "removeLogin")
	public String removeLogin(HttpSession session){
		session.removeAttribute("loginUser");
		return "login";
	}
}
